package com.tnovoselec.android.travelassistant.parser;

import java.util.ArrayList;
import java.util.List;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.tnovoselec.android.travelassistant.dto.GasPriceDto;

public class GasPricesParser extends DefaultHandler {

	private StringBuilder buffer;

	private final static String TAG_PRICES = "prices";

	private final static String TAG_NAME = "name";
	private final static String TAG_PRICE = "price";

	private boolean inPrices = false;
	private boolean inName = false;
	private boolean inPrice = false;

	private GasPriceDto tempGasPrice;
	private List<GasPriceDto> prices;

	@Override
	public void startDocument() throws SAXException {
		prices = new ArrayList<GasPriceDto>();
	}

	@Override
	public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
		buffer = new StringBuilder("");

		if (localName.equalsIgnoreCase(TAG_PRICES)) {
			inPrices = true;
			tempGasPrice = new GasPriceDto();
		} else if (localName.equalsIgnoreCase(TAG_NAME)) {
			inName = true;
		} else if (localName.equalsIgnoreCase(TAG_PRICE)) {
			inPrice = true;
		}

	}

	@Override
	public void endElement(String uri, String localName, String qName) throws SAXException {
		if (inPrices) {
			if (inName) {
				tempGasPrice.setName(buffer.toString());
			} else if (inPrice) {
				tempGasPrice.setPrice(buffer.toString());
			}
		}
		if (localName.equalsIgnoreCase(TAG_PRICES)) {
			inPrices = false;
			prices.add(tempGasPrice);
		} else if (localName.equalsIgnoreCase(TAG_NAME)) {
			inName = false;
		} else if (localName.equalsIgnoreCase(TAG_PRICE)) {
			inPrice = false;
		}
	}

	@Override
	public void characters(char[] ch, int start, int length) throws SAXException {
		buffer.append(String.valueOf(ch, start, length));
	}

	public List<GasPriceDto> getPrices() {
		return prices;
	}
}
